import java.util.HashMap;
import java.util.Map;

/**
 * 根据一棵树的前序遍历与中序遍历构造二叉树。
 * 前（根）序遍历 ：中左右
 * 中（根）序遍历：左中右
 * <p>
 * 例如，给出
 * <p>
 * 前序遍历 preorder = [3,9,20,15,7]
 * 中序遍历 inorder = [9,3,15,20,7]
 * <p>
 * 注意:
 * 你可以假设树中没有重复的元素。
 */
class Solution {

    public static void main(String[] args) {
        System.out.println(buildTree(new int[]{1}, new int[]{1}));
        // System.out.println(buildTree(new int[]{1, 2}, new int[]{1, 2}));
        // System.out.println(buildTree(new int[]{9, 3, 15, 20, 7}, new int[]{9, 15, 7, 20, 3}));
        // System.out.println(buildTree(new int[]{4, 2, 5, 1, 6, 3, 7}, new int[]{4, 5, 2, 6, 7, 3, 1}));
    }

    private static Map<Integer, Integer> map;

    /**
     * 用递归的方法去做
     *
     * @param inorder
     * @param postorder
     * @return
     */
    public static TreeNode buildTree(int[] inorder, int[] postorder) {
        int val = postorder[postorder.length - 1];
        TreeNode root = new TreeNode(val);
        map = new HashMap<>(postorder.length * 2);
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        int i = map.get(val);
        root.left = buildTree(inorder, 0, i - 1, postorder, 0, i - 1);
        root.right = buildTree(inorder, i + 1, inorder.length - 1, postorder, i, postorder.length - 2);
        return root;
    }


    public static TreeNode buildTree(int[] inorder, int pos1, int pos2, int[] postorder, int pos3, int pos4) {
        if (pos1 == inorder.length || pos1 > pos2) {
            return null;
        }
        int val = postorder[pos4];
        TreeNode root = new TreeNode(val);
        if (pos1 == pos2) {
            return root;
        }
        int i = map.get(val) - pos1;
        root.left = buildTree(inorder, pos1, pos1 + i - 1, postorder, pos3, pos3 + i - 1);
        root.right = buildTree(inorder, pos1 + i + 1, pos2, postorder, pos3 + i, pos4 - 1);
        return root;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}